<?php

declare(strict_types=1);

namespace App\Common\Helpers;

use Mine\Exception\NormalStatusException;

class Aes
{

    private const KEY = 'BWwlSYDSUf3Du9iA';

    private const IV = 'B32CoSydSS1YPuG8';

    public static function encrypt(string $plaintext): string
    {
        $ciphertext = \openssl_encrypt($plaintext, 'aes-128-cbc', self::KEY, OPENSSL_RAW_DATA, (string) self::IV);

        if ($ciphertext === false) {
            throw new NormalStatusException(openssl_error_string() ?: 'Encrypt AES CBC error.');
        }

        return base64_encode($ciphertext);
    }


    public static function decrypt(string $ciphertext): string
    {
        $plaintext = openssl_decrypt(
            base64_decode($ciphertext),
            'aes-128-cbc',
            self::KEY,
            OPENSSL_RAW_DATA,
            (string) self::IV
        );

        if ($plaintext === false) {
            throw new NormalStatusException(openssl_error_string() ?: 'Decrypt AES CBC error.');
        }

        return $plaintext;
    }
}